import React from 'react';
import {
  Dimensions,
  PixelRatio,
  StyleSheet,
  View,
  TouchableOpacity,
  Platform,
  TouchableNativeFeedback,
  PermissionsAndroid,
} from 'react-native';
import Icon from 'react-native-vector-icons/Entypo';
import moment from '../commons/moment';
import {
  PageOederProductParams,
  ProductFieldToCategoryMapping,
  ProductParams,
  ProductType,
} from '../reducers/constant';
import _ from 'lodash';
import {v4 as uuid} from 'uuid';
import {I18n} from '../reducers/intl';

const DEVICE_WIDTH = Dimensions.get('screen').width;
const DEVICE_HEIGHT = Dimensions.get('screen').height;

export function getRealSize(size) {
  if (size === 1) {
    return StyleSheet.hairlineWidth;
  }
  return PixelRatio.roundToNearestPixel((DEVICE_WIDTH / 375) * size);
}

const Touchable =
  Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;

export function isTopRoute(nav) {
  const r = nav.routes[nav.index];
  if (r.routeName === 'Main') {
    const m = r.routes[r.index];
    if (m.index === 0) {
      return true;
    }
    return false;
  } else {
    if (r.index === 0) {
      return true;
    }
    return false;
  }
}

const createNavigationOptions = (
  title = '未定义',
  navigation,
  rightView = null,
  leftView = 'default',
  onBack = null,
) => {
  const headerLeft =
    leftView === 'default' ? (
      <View>
        <TouchableOpacity
          style={styles.buttonStyle}
          onPress={() => navigation.pop()}
          underlayColor="transparent">
          <Icon name="chevron-small-left" size={35} />
        </TouchableOpacity>
      </View>
    ) : (
      leftView
    );
  return {
    title,
    headerLeft,
  };
};

const styles = StyleSheet.create({
  buttonStyle: {
    width: 40,
    height: 40,
  },
});

const RequestCameraPermission = async () => {
  if (Platform.OS === 'ios') {
    return true;
  }
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        title: 'App Camera Permission',
        message: 'App needs access to your camera ',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('Camera permission given');
    } else {
      console.log('Camera permission denied');
      throw new Error(I18n.t('toast.noPermission'));
    }
  } catch (err) {
    throw err;
  }
};

const formatDate = (date, formatString) => {
  return moment(date || new Date()).format(formatString || 'YYYY-MM-DD');
};

const SelectionSummary = (items = [], selections = []) => {
  const result = selections.filter(s => items.includes(s.id));
  return result.map(r => r.name).join(',');
};

const ConvertProduct = (item, category) => {
  const product = {
    uid: uuid(),
    redo: item.redo,
  };
  let productId;
  if (item.type === ProductType.fixed) {
    product.type = ProductType.fixed;
    productId = _.get(item, 'fixed_product.id');
    if (!productId) {
      productId = _.get(item, 'fixed_product');
    }
    product.product = category.fixedproduct.find(fp => fp.id === productId);
    // if (!product.product) {
    //   product.product = category.fixedproduct.find(
    //     fp => fp.id === item.fixed_product.id,
    //   );
    // }
  } else {
    product.type = ProductType.remvArch;
    productId = _.get(item, 'remv_arch.id');
    if (!productId) {
      productId = _.get(item, 'remv_arch');
    }
    product.product = category.remvarchproduct.find(mp => mp.id === productId);
    // if (!product.product) {
    //   product.product = category.fixedproduct.find(
    //     fp => fp.id === item.remv_arch.id,
    //   );
    // }
  }
  const OrderParams = PageOederProductParams[product.type];
  for (const key in OrderParams) {
    const value = item[OrderParams[key]];
    // console.log('key', OrderParams[key], value);
    if (value) {
      if (Array.isArray(value)) {
        if (value.length) {
          product[key] = value.map(vid =>
            category[ProductFieldToCategoryMapping[product.type][key]].find(
              o => o.id === vid,
            ),
          );
        }
      } else {
        product[key] = category[
          ProductFieldToCategoryMapping[product.type][key]
        ].find(o => o.id === (value.id || value));
      }
    }
  }
  product.summary = SummaryParams(product);
  return product;
};

const SummaryParams = product => {
  const params = [];
  const productType = product.product ? product.product.type : product.type;
  const type =
    productType === ProductType.fixed
      ? ProductType.fixed
      : ProductType.remvArch;

  params.push(`type:${type}`);
  if (product.gum) {
    params.push(`gum:${product.gum.join(',')}`);
  }
  if (product.join) {
    params.push(`join:${product.join.join(',')}`);
  }
  Object.values(ProductParams[type]).forEach(param => {
    const value = product[param];
    if (value) {
      if (Array.isArray(value)) {
        params.push(`${param}:${value.map(v => (v ? v.name : '')).join(',')}`);
      } else {
        params.push(`${param}:${value.name}`);
      }
    }
  });
  return params.join(' / ');
};

export {
  formatDate,
  createNavigationOptions,
  DEVICE_WIDTH,
  DEVICE_HEIGHT,
  Touchable,
  SelectionSummary,
  SummaryParams,
  ConvertProduct,
  RequestCameraPermission,
};
